package com.mrcode.neptuneproject.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mrcode.neptuneproject.common.Result;
import com.mrcode.neptuneproject.service.ChatGptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author YSH
 * @Date 2023/5/31 19:06
 * @Version 1.0
 */
@Slf4j
@Service
public class ChatGPTServiceImpl implements ChatGptService {

    @Value("${chatGpt.apikey}")
    private String apiKey;
    @Value("${chatGpt.address}")
    private String address;

    @Override
    public Result<String> getChatGptAnswer(String prompt) {
        // 构建请求的JSON数据
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("model", "gpt-3.5-turbo");
        List<Map<String, String>> dataList = new ArrayList<>();
        dataList.add(new HashMap<String, String>(2) {{
            put("role", "user");
            put("content", prompt);
        }});
        paramMap.put("messages", dataList);
        RequestConfig config = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000).build();
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost req = new HttpPost(address);
        req.setConfig(config);
        req.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);
        req.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        req.setEntity(new StringEntity(JSONObject.toJSONString(paramMap), ContentType.APPLICATION_JSON));
        String responseBody = "";
        try {
            log.info("调用GPT API，request is:" + paramMap);
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(req);
            HttpEntity responseEntity = response.getEntity();
            responseBody = EntityUtils.toString(responseEntity);
            // 处理响应数据
            log.info("调用GPT API，response is:" + responseBody);
        } catch (Exception e) {
            return Result.error("调用GPT API出错！ ERROR IS：" + e);
        }
        if (!StringUtils.hasText(responseBody)) {
            return Result.error("调用GPT API返回结果为空！");
        }
        String message = JSONArray.parse(JSONObject.parseObject(responseBody).get("choices").toString()).stream().findFirst().orElse("").toString();
        return Result.success(JSONObject.parseObject(message).getJSONObject("message").get("content").toString());
    }
}
